package com.hxci.web.filter;

import com.hxci.web.bean.WhitelistUrl;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;


 // 过滤所有请求
//@WebFilter("/*")
public class URLfiflt implements Filter {

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        HttpServletRequest httpRequest = (HttpServletRequest) request;
        HttpServletResponse httpResponse = (HttpServletResponse) response;

        // 获取当前请求的URL
        String requestURI = httpRequest.getRequestURI();


//         检查是否是公开的URL（如登录页面、注册页面等）
        List<String> publicUrls = WhitelistUrl.whitelist();
        boolean isPublicUrl = publicUrls.stream().anyMatch(url -> requestURI.equals(url) || requestURI.startsWith(url + "/"));
        if ( isPublicUrl) {
            // 如果是公开的URL，则直接放行
            chain.doFilter(request, response); // 继续执行过滤器链
            return;
        }


        // 获取当前会话
        HttpSession session = httpRequest.getSession(false);
        // 检查用户是否已登录
        if (session != null && session.getAttribute("login_account") != null) {
            chain.doFilter(request, response); // 继续执行过滤器链
        } else {
            // 用户未登录，重定向到登录页面
            httpResponse.sendRedirect(httpRequest.getContextPath() + "/index.jsp");
        }
    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        // 初始化过滤器
    }

    @Override
    public void destroy() {
        // 销毁过滤器
    }
}
